<?php
/**
 * 自定义config配置类
 * Created by PhpStorm.
 * User: zgh
 * Date: 2021-08-04
 * Time: 10:19
 */

namespace app\common\service;


use app\common\util\CacheUtil;
use think\Db;


class ConfigService
{

    public static function clearDbCache()
    {
        CacheUtil::clear(\CacheKeyMap::configHash());
    }

    public static function getDbConfig()
    {
        return CacheUtil::getAndSet(\CacheKeyMap::configHash(), function () {
            return ConfigService::queryDbConfig();
        });
    }

    public static function queryDbConfig()
    {
        $data = Db::name('config')->where(["status" => 1])->field('type,name,value')->select();
        $config = [];
        if ($data && is_array($data)) {
            foreach ($data as $value) {
                $config[$value['name']] = self::parseDbConfig($value['type'], $value['value']);
            }
        }
        return $config;
    }

    public static function parseDbConfig($type, $value)
    {
        switch ($type) {
            case 1: //解析数组
                $array = preg_split('/[,;' . PHP_EOL . ']+/', trim($value, ",;" . PHP_EOL . ""));
                if (strpos($value, ':')) {
                    $value = array();
                    foreach ($array as $val) {
                        list($k, $v) = explode(':', $val);
                        $value[$k] = $v;
                    }
                } else {
                    $value = $array;
                }
                break;
        }
        return $value;
    }
}